package cn.satoken.controller;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.satoken.entity.SysUser;
import cn.satoken.mapper.SysUserMapper;
import cn.satoken.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

import static cn.satoken.common.ValueValid.ensureColumnValueValid;
import static cn.satoken.constant.StatusConstant.*;

/**
 * <h3>saToken</h3>
 * <p></p>
 *
 * @author gdw
 * @since 2025-02-07 09:49:55
 */
@RestController
@RequestMapping("/user/")
@RequiredArgsConstructor
public class LoginController {
    private final SysUserMapper sysUserMapper;
    private final SysUserService sysUserService;
    private final SimpMessagingTemplate messagingTemplate;

    /**
     *
     * 登陆
     * @param user
     * @return
     */
    @RequestMapping("login")
    public SaResult login(@RequestBody SysUser user, HttpSession session) {
        String inputCaptcha = user.getCaptcha(); // 用户提交的验证码
        String sessionCaptcha = (String) session.getAttribute("captcha"); // 服务端 session 中的验证码

        if (sessionCaptcha == null || !sessionCaptcha.equalsIgnoreCase(inputCaptcha)) {
            return SaResult.error("验证码错误");
        }
        return sysUserService.login(user,session);
    }

    /**
     * 退出
     * @param phone
     * @return
     */
    @RequestMapping("outlogin/{phone}")
    public SaResult outlogin(@PathVariable String phone) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getPhone, phone);
        SysUser sysUser = sysUserMapper.selectOne(wrapper);
        StpUtil.logout(phone);
        messagingTemplate.convertAndSend("/topic/login",sysUser.getName()+"用户，下线！");
        return SaResult.ok(USER_LOGIN_OUT);
    }

    /**
     * 修改
     * @param user
     * @return
     */
    @RequestMapping("update")
    @Transactional
    public SaResult update(@RequestBody SysUser user) {
       if(!ensureColumnValueValid(user.getId(),SysUser::getId, sysUserMapper::selectOne)) return SaResult.error("未传递用户id");
       sysUserMapper.updateById(user);
       StpUtil.logout(user.getPhone() );
       return SaResult.ok(UPDATE_SUCCESS);
    }
}
